<template>
  <div v-loading="isLoadingData">
    <el-table :data="logs" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="nickname" label="用户名称" width="180" />
      <el-table-column prop="method" label="操作类型" width="180" />
      <el-table-column prop="state" label="操作内容" width="180" />
      <el-table-column prop="ip" label="操作IP" width="180" />
      <el-table-column prop="time" label="操作时间" width="180" />
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            link
            type="primary"
            @click="searchUser(logs[scope.$index].uid)"
            >查看操作用户</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page"
      background
      :page-size="limit"
      layout="prev, pager, next, jumper"
      :total="total"
      style="margin: 2rem 0"
    />
  </div>
</template>
<script lang="ts">
import Method from '@/globalmethods.ts'
import { ElMessage } from 'element-plus'
import { watch } from 'vue'
import { res } from '../type.ts'

export default {
  name: 'admin-site',
  data() {
    return {
      page: 1,
      limit: 15,
      total: 0,
      isLoadingData: false,
      logs: [] as any,
    }
  },
  methods: {
    /**
     * 获取日志
     */
    adminLog() {
      this.isLoadingData = true
      Method.api_post('/log/getAdminLog', {
        page: this.page,
        limit: this.limit,
      }).then((response) => {
        this.isLoadingData = false
        let res = <res>response.data
        console.log('res', res)

        if (res.code == 200) {
          for (const el of res.data) {
            el.time = Method.formatNormalTime(el.time)
            try {
              el.state = /^.*{"/.test(el.state)
                ? el.method +
                  el.state.match(/\[\d+\]/)[0] +
                  JSON.stringify(JSON.parse(el.state.replace(/^.*{"/, '{"')))
                : el.state
            } catch (error) {}
          }
          console.log(this.page, this.limit, res.sum)

          this.logs = res.data
          if (this.page == 1) this.total = res.sum
        } else {
          ElMessage({
            type: 'error',
            message: '获取失败',
          })
        }
      })
    },
    /**
     * 查询用户
     */
    searchUser(id: number) {
      this.$router.push({
        path: '/admin/account',
        query: {
          search: String(id),
          search_type: 0,
        },
      })
    },
  },
  mounted() {
    this.adminLog()
    watch(
      () => this.page,
      () => {
        this.adminLog()
      },
    )
  },
}
</script>
